import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:image_picker/image_picker.dart';
import 'package:photo_frame/dialog/bind_frame_dialog.dart';
import 'package:photo_frame/pages/gallery/gallery_photo_provider.dart';
import 'package:photo_frame/pages/gallery/widget/gallery_select_asset_button.dart';
import 'package:photo_frame/provider/app_trans_asset_provider.dart';
import 'package:photo_frame/provider/frames_provider.dart';
import 'package:photo_frame/router/router_context.dart';
import 'package:photo_frame/utils/a_logger.dart';
import 'package:photo_frame/utils/app_const.dart';
import 'package:photo_frame/utils/localization_util.dart';
import 'package:photo_frame/widgets/app_asset_video_widget.dart';
import 'package:photo_frame/widgets/app_bar_widget.dart';
import 'package:photo_frame/widgets/app_asset_image_widget.dart';
import 'package:photo_manager/photo_manager.dart';
import 'package:photo_manager_image_provider/photo_manager_image_provider.dart';
import 'package:provider/provider.dart';

class GalleryPage extends StatefulWidget {
  const GalleryPage();

  @override
  State createState() => _GalleryPageState();
}

class _GalleryPageState extends State<GalleryPage>
    with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;
  final ImagePicker assetPicker = ImagePicker();
  GalleryPhotoProvider aseetProvider = GalleryPhotoProvider();
  ScrollController controller = ScrollController();
  GlobalKey<RefreshIndicatorState> refreshIndicatorStateKey = GlobalKey();
  bool multiSelectMode = false;

  @override
  initState() {
    super.initState();
    initAsset();
    initDataBase();
  }

  @override
  void dispose() {
    super.dispose();
  }

  initAsset() async {
    print("init asset");
    bool hasAccess = await aseetProvider.requestPermission();
    if (!hasAccess) {
      EasyLoading.showToast(
          appLocalForContext(context).galleryRequestPermissionToast);
      return;
    }
    await refreshAsset();
  }

  refreshAsset() async {
    await aseetProvider.refreshAssetPath();
    await aseetProvider.refreshAssets();
  }

  initDataBase() async {
    await aseetProvider.initDataBase();
  }

  takeNewPhoto(GalleryPhotoProvider provider) async {
    XFile? imageFile = await assetPicker.pickImage(source: ImageSource.camera);
    if (imageFile == null) {
      ALogger.d("imageFile ==null");
      EasyLoading.showToast(appLocalForContext(context).takePhotoFail);
      return;
    }
    final Uint8List imageBytes = await imageFile.readAsBytes();
    ALogger.d("imageBytes ${imageBytes.length}");
    final AssetEntity? asset = await PhotoManager.editor.saveImage(
        filename: "${DateTime.now().millisecondsSinceEpoch}.png",
        title: "${DateTime.now().millisecondsSinceEpoch}.png",
        imageBytes);
    if (asset == null) {
      EasyLoading.showToast(appLocal().takePhotoFail);
      return;
    }
    refreshIndicatorStateKey.currentState?.show();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return ChangeNotifierProvider<GalleryPhotoProvider>(
        create: (context) => aseetProvider,
        child: Scaffold(
          appBar: commonAppBar(appLocalForContext(context).gallery,
              hideBack: true,
              leading: buildLeftNavbarItem(context),
              actions: [buildRightNavbarItem(aseetProvider)]),
          body: SafeArea(
            child: Column(
              children: [
                Consumer<GalleryPhotoProvider>(
                    builder: (context, provider, child) {
                  return Container(
                      color: Colors.black,
                      height: 300,
                      child: Stack(children: [
                        Center(
                            child: buildPreviewWidget(
                                provider.currentPreviewAsset)),
                        Positioned(
                            bottom: 15,
                            right: 15,
                            child: GallerySelectAssetButton(
                                multiSelectMode: multiSelectMode,
                                onPressed: (value) {
                                  multiSelectMode = !multiSelectMode;
                                  provider.clearSelectAssets();
                                  if (multiSelectMode &&
                                      provider.currentPreviewAsset != null) {
                                    provider.triggerCollectAsset(
                                        provider.currentPreviewAsset!);
                                  }
                                })),
                        Positioned(
                            top: 10,
                            left: 0,
                            child: buildAssetPathsMenu(provider)),
                      ]));
                }),
                Flexible(child: Consumer(builder: buildBody)),
              ],
            ),
          ),
        ));
  }

  Widget buildBody(
      BuildContext context, GalleryPhotoProvider provider, Widget? child) {
    return RefreshIndicator(
      color: Color(0xff3F74EF),
      key: refreshIndicatorStateKey,
      onRefresh: () async {
        await refreshAsset();
      },
      child: GridView.custom(
        controller: controller,
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 4, mainAxisSpacing: 5, crossAxisSpacing: 5),
        childrenDelegate: SliverChildBuilderDelegate(
          (BuildContext context, int index) {
            if (index == provider.assetList.length - 8) {
              provider.loadMoreAssets();
            }
            if (index == 0) {
              return CupertinoButton(
                padding: EdgeInsets.zero,
                onPressed: () {
                  takeNewPhoto(provider);
                },
                child: Image.asset("images/pic_gallery_camera.png"),
              );
            }
            final AssetEntity entity = provider.assetList[index - 1];
            return AppAssetImageWidget(
              onPreview: provider.currentPreviewAsset != null &&
                  (provider.currentPreviewAsset!.id == entity.id),
              selected: provider.containAsset(entity.id),
              hasSend: provider.hasSendAsset(entity.id),
              key: ValueKey<int>(index),
              showSelectMark: multiSelectMode,
              entity: entity,
              option: const ThumbnailOption(size: ThumbnailSize.square(200)),
              idx: provider.assetPosition(entity.id),
              onTap: () {
                if (multiSelectMode) {
                  provider.triggerCollectAsset(entity);
                }
                provider.chosePreviewAsset(entity);
              },
              onLongPress: () {
                if (!multiSelectMode) {
                  multiSelectMode = true;
                  provider.clearSelectAssets();
                  provider.chosePreviewAsset(entity);
                  provider.triggerCollectAsset(provider.currentPreviewAsset!);
                }
              },
            );
          },
          childCount: provider.assetList.length + 1,
          findChildIndexCallback: (Key key) {
            // Re-use elements.
            if (key is ValueKey<int>) {
              return key.value;
            }
            return null;
          },
        ),
      ),
    );
  }

  printMimeType(AssetEntity? asset) async {
    print(await asset!.mimeTypeAsync);
  }

  buildPreviewWidget(AssetEntity? asset) {
    if (asset == null) return SizedBox();
    if (asset.type == AssetType.audio || asset.type == AssetType.video) {
      return AppAssetVideoWidget(
        entity: asset,
        usingMediaUrl: true,
      );
    } else {
      return AssetEntityImage(
        asset,
        width: MediaQuery.of(context).size.width,
        height: 300,
        fit: BoxFit.contain,
      );
    }
  }

  buildAssetPathsMenu(GalleryPhotoProvider provider) {
    return MenuAnchor(
      style: MenuStyle(
          backgroundColor: WidgetStateProperty.all(Colors.white),
          maximumSize: WidgetStateProperty.all(Size(200, 400)), // 设置最大尺寸
          shape: WidgetStateProperty.all(RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12), // 设置圆角
          ))),
      alignmentOffset: Offset(10, -5),
      menuChildren: provider.pathAdapterList.isNotEmpty
          ? provider.pathAdapterList.map((pathAdapter) {
              return MenuItemButton(
                  onPressed: () {
                    provider.updateAssetPath(pathAdapter.assetPath.id);
                  },
                  child: Row(children: [
                    Container(
                      decoration:
                          BoxDecoration(borderRadius: BorderRadius.circular(4)),
                      child: AssetEntityImage(
                          width: 40,
                          height: 40,
                          pathAdapter.previewAsset,
                          fit: BoxFit.cover,
                          isOriginal: false),
                    ),
                    SizedBox(width: 4),
                    Text(pathAdapter.assetPath.name)
                  ]));
            }).toList()
          : [],
      builder:
          (BuildContext context, MenuController controller, Widget? child) {
        return CupertinoButton(
          padding: EdgeInsets.only(top: 0, bottom: 0, left: 10, right: 15),
          onPressed: () {
            if (controller.isOpen) {
              controller.close();
            } else {
              controller.open();
            }
          },
          child: Container(
              padding: EdgeInsets.only(left: 15, right: 15),
              height: 30,
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(15),
                  color: Color(0xeeffffff)),
              child: Center(
                  child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                    Text(provider.pathAdapter?.assetPath.name ?? "",
                        style:
                            TextStyle(color: Color(0xff222222), fontSize: 14)),
                    SizedBox(width: 2),
                    Image.asset("images/icon_down_arrow.png",
                        width: 8, height: 4)
                  ]))),
        );
      },
    );
  }

  buildLeftNavbarItem(BuildContext context) {
    return CupertinoButton(
      padding: EdgeInsets.zero,
      onPressed: () {
        showDialog(context: context, builder: (context) => BindFrameDialog()).whenComplete((){
          context.read<FramesViewModel>().fetch();
        });
      },
      child: Padding(
        padding: const EdgeInsets.only(left: 15),
        child: Align(
          alignment: Alignment.centerLeft,
          child: Image.asset(
            "images/icon_gallery_add_frame.png",
            fit: BoxFit.contain,
            width: 25,
            height: 25,
          ),
        ),
      ),
    );
  }

  buildRightNavbarItem(GalleryPhotoProvider provider) {
    return CupertinoButton(
      padding: EdgeInsets.zero,
      onPressed: () {
        if (provider.currentPreviewAsset?.type == AssetType.video) {
          if ((provider.currentPreviewAsset?.duration ?? 0) > 5 * 60) {
            EasyLoading.showToast(appLocal().videoTooLong);
            return;
          }
        }
        List<String> assetIds = multiSelectMode
            ? provider.selectedAssetMap.values.map((asset) => asset.id).toList()
            : [provider.currentPreviewAsset?.id ?? ""];
        if (assetIds.isEmpty) {
          EasyLoading.showToast(
              appLocalForContext(context).atLeastChooseOnPicture);
          return;
        }
        multiSelectMode = false;
        provider.clearSelectAssets();
        AppAssetTransProvider.provider()
            .updateTransAssetBuffer("assetIds", assetIds);
        ARouter.instance.pagePush("/selectFrame",
            arguments: {"source": SelectFrameSource.GALLERY}).then((e) {
          refreshAsset();
        });
      },
      child: actionTextWidget(appLocalForContext(context).next),
    );
  }
}
